<template>
  <div id="createRule">
    <el-dialog
      title="创建编号"
      width="510px"
      :visible.sync="dialogData.isShow"
      :before-close="labelHandleClose"
    >
      <el-form
        ref="ruleForm"
        :model="ruleForm"
        :rules="rules"
        label-width="90px"
        label-position="right"
        class="addForm"
      >
        <el-form-item label="编号名称" prop="name">
          <el-input
            v-model="ruleForm.name"
            placeholder="请输入"
            maxlength="30"
            show-word-limit
            :disabled="isEdit"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item label="编号描述" prop="describe">
          <el-input
            v-model="ruleForm.describe"
            type="textarea"
            placeholder="请输入"
            maxlength="300"
            show-word-limit
            :disabled="isEdit"
          ></el-input>
        </el-form-item>
        <el-form-item label="添加方式" prop="importType">
          <el-radio
            v-for="item in orderList"
            :key="item.value"
            v-model="ruleForm.importType"
            :label="item.value"
          >
            {{ item.label }}
          </el-radio>
        </el-form-item>
        <template v-if="ruleForm.importType === 'input'">
          <!--手动添加-->
          <el-form-item label="输入大鹏号" prop="users">
            <el-select
              v-model="ruleForm.users"
              multiple
              filterable
              remote
              :no-data-text="noData"
              placeholder="请输入大鹏号"
              :remote-method="remoteMethod"
              :loading="searchLoading"
              value-key="dpNumber"
              clearable
            >
              <el-option
                v-for="item in options"
                :key="item.userId"
                :label="item.dpNumber"
                :value="item"
                :disabled="ruleForm.users.length >= 5"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </template>
        <template v-else>
          <!--批量导入-->
          <el-form-item label="批量导入" prop="users">
            <importAutoFile
              :dialogData="fileData"
              @getUsers="getUsers"
              @showError="showError"
            ></importAutoFile>
          </el-form-item>
        </template>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="success" plain @click="cancelLabel">
          取 消
        </el-button>
        <el-button
          type="success"
          :loading="loading"
          @click.prevent="confirmLabel('ruleForm')"
        >
          确 定
        </el-button>
      </div>
    </el-dialog>
    <!-- 导入失败弹窗 -->
    <errorDialog
      v-if="errorDialogData.isShow"
      :dialog-data="errorDialogData"
      from="userRule"
    ></errorDialog>
  </div>
</template>
<script>
import {
  getNumberDetail,
  addNum,
  editNum
} from '@/api/activeManagement/templatePage' // 接口
import { getDpNum, importUrl, downloadUrl } from '@/api/system/user' // 接口
import importAutoFile from '@common/importFileAuto' // 导入
import errorDialog from '@common/errorDialog' // 导入失败弹窗
export default {
  name: 'CreateRule',
  msg: '创建活动-预置用户规则-创建编号弹窗',
  components: {
    importAutoFile,
    errorDialog
  },
  props: ['dialogData'],
  data() {
    return {
      id: '', //活动id
      options: [], //大鹏号下拉框列表
      noData: '请再输入至少10个字符',
      list: [], //根据搜索关键字，请求返回的数据
      searchLoading: false, //远程搜索loading
      loading: false,
      isAdd: true, // 新增-true,编辑-false
      /*  loading: true,*/
      // 表单数据
      ruleForm: {
        name: '', // 编号名称
        describe: '', //编号描述
        importType: 'input', // 添加方式
        users: [] // 大鹏号
      },
      // 导入失败弹框的数据
      errorDialogData: {
        isShow: false, // 控制弹框显示
        warningText: '' // 参数
      },
      orderList: [
        {
          value: 'input',
          label: '手动添加'
        },
        {
          value: 'import',
          label: '批量导入'
        }
      ],
      rules: {
        name: [{ required: true, message: '请输入编号名称', trigger: 'blur' }]
      },
      fileData: {
        url: '', // 导入接口
        downUrl: '', // 下载模板接口
        users: [] // 上传成功后，返回的users
      }
    }
  },
  watch: {
    'ruleForm.importType': {
      handler(newV, oldV) {
        if (newV === 'input') {
          this.fileData.users = []
        }
        //导入方式切换，清空之前的数据
        this.ruleForm.users = []
      },
      deep: 'true'
    }
  },
  computed: {
    isEdit() {
      return this.dialogData.type === 'edit'
    }
  },
  mounted() {
    this.$set(this.fileData, 'url', importUrl())
    this.$set(this.fileData, 'downUrl', downloadUrl())
    this.id = this.$route.query.id
    if (this.dialogData.type === 'edit' && this.dialogData.id) {
      this.getFormData()
    }
  },
  methods: {
    /*编辑状态-获取表单内容*/
    getFormData() {
      getNumberDetail(
        this.id,
        this.dialogData.id,
        (response) => {
          let { name, describe } = response
          this.ruleForm.name = name
          this.ruleForm.describe = describe
        },
        (response) => {
          this.$message.warning(response.message)
        }
      )
    },
    /*获取大鹏号*/
    getDapengNum(dpAccounts) {
      return new Promise((resolve, reject) => {
        let obj = { type: 'DPACCOUNT', value: dpAccounts }
        getDpNum(
          obj,
          (response) => {
            resolve(response.rows)
          },
          (response) => {
            this.$message.warning(response.message)
            resolve([])
          }
        )
      })
    },
    /*输入框内容改变时，执行*/
    async remoteMethod(query) {
      query = query.trim()
      let _this = this
      if (query.length > 9) {
        _this.inputLoading = true
        let ary = await this.getDapengNum(query)
        if (ary.length === 0) {
          setTimeout(() => {
            _this.options = []
            _this.inputLoading = false
            this.noData = '没有找到匹配大鹏号'
          }, 200)
        } else {
          setTimeout(() => {
            _this.options = [...ary]
            _this.inputLoading = false
            /* console.log("this.options=",this.options)*/
          }, 200)
        }
      } else {
        _this.options = []
        let n = 10 - query.length
        this.noData = `请再输入${n}个字符`
      }
    },
    labelHandleClose(done) {
      this.cancelLabel()
      done()
    },
    cancelLabel() {
      // 关闭前清空
      this.loading = false
      this.dialogData.isShow = false
      this.dialogData.type = ''
      this.dialogData.id = ''
    },
    /*批量导入文件-成功*/
    getUsers(obj) {
      this.ruleForm.users = [...obj]
    },
    confirmLabel(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.subHand()
        } else {
          return false
        }
      })
    },
    /* 提交表单-手动导入 */
    subHand() {
      //手动导入
      this.loading = true
      let url = ''
      let method = ''
      let obj = { ...this.ruleForm }
      delete obj.importType
      if (this.dialogData.type === 'edit') {
        //编辑
        editNum(
          this.id,
          this.dialogData.id,
          obj,
          (response) => {
            this.loading = false
            this.$emit('refresh')
            this.cancelLabel()
          },
          (response) => {
            // 上传失败
            this.loading = false
            this.$message.warning(response.message)
          }
        )
      } else {
        //新增
        addNum(
          this.id,
          obj,
          (response) => {
            this.loading = false
            this.$emit('refresh')
            this.cancelLabel()
          },
          (response) => {
            // 上传失败
            this.loading = false
            this.$message.warning(response.message)
          }
        )
      }
    },
    /* 导入失败弹窗 */
    showError(text) {
      this.errorDialogData.isShow = true // 显示导入失败弹框
      this.errorDialogData.warningText = text // 显示导入失败弹框
    }
  }
}
</script>
<style lang="less">
#createRule {
  .el-input__inner {
    padding-right: 75px;
  }
  .el-dialog {
    border-radius: 4px;
    .el-dialog__header {
      border-bottom: 1px solid rgba(225, 228, 233, 1);
    }
  }
  .list {
    margin-top: 15px;
  }
  .title {
    border-left: 3px solid #1dc8a4;
    height: 12px;
    line-height: 12px;
  }
  .el-upload {
    /*  float:left;*/
    text-align: left;
  }
  .el-select {
    width: 100%;
  }
}
</style>
